<?php
class FileSystem extends Model{
	public $_table = 'attachment';

	public function upload(){
		$limit = array(
			'type'=>array('gif','jpeg','jpg','png'),
			'size'=>50*1024*1024
		);
		$tmp = $_FILES['userfile']['tmp_name'];
		$size = $_FILES['userfile']['size'];

		$oldfile= $_FILES['userfile']['name'];
		$pos = strrpos($oldfile,'.');
		if($pos===false) return false;

		$type = substr($oldfile,$pos+1);
		if(array_search($type,$limit['type'])===false || $size > $limit['size']){
			return false;
		}

		$newfile = md5('zhoubc'.date('Ymdhis')).'.'.$type;

		if(!move_uploaded_file($tmp,UPLOAD_ROOT.$newfile)){
			return false;
		}

		$thumb = Core::getInstance()->sys_load_class('Thumb');
		$width = isset($_POST['width'])?intval($_POST['width']):200;
		$height = isset($_POST['height'])?intval($_POST['height']):200;
		$thumb->resizeImg(UPLOAD_ROOT.$newfile,UPLOAD_ROOT.'thumb_'.$newfile,$width,$height);

		$arr = array(
			'`oldfile`'=>"'{$oldfile}'",
			'`newfile`'=>"'{$newfile}'",
			'`thumb`'=>"'thumb_{$newfile}'",
		);

		if(isset($_POST['title']) && !empty($_POST['title'])){
			$arr['`oldfile`']="'".Character::HTMLToDbEncode($_POST['title'])."'";
		}
		return $this->addDb($arr);
	}

	public function addDb($arr){
		return $this->add($arr);
	}

	public function delData($id){
		$data = $this->getOneData($id);
        @unlink(UPLOAD_ROOT.$data['newfile']); // 删除文件
        @unlink(UPLOAD_ROOT.$data['thumb']); // 删除多略图
		$this->del($id);
	}

	public function getOneData($id){
		$sql = "select * from {$this->_table} where `id`=".intval($id);
		return $this->getOne($sql);
	}
}

